<?php
namespace phpexcel;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

class PHPExcel
{
    public static function download($data, $filename = '', $widtharray = [], $settings = [])
    {
        $letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        if ($filename === '') {
            $filename = date('YmdHis');
        }
        $spreadsheet = new Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();
        for ($i = 1; $i <= count($data); $i++) {
            $j = 0;
            foreach ($data[$i - 1] as $value) {
                $cell = $letter[$j] . $i;
                $sheet->getStyle($cell)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
                $sheet->getStyle($cell)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
                $sheet->setCellValue($cell, $value);
                $j++;
            }
        }
        if (!empty($widtharray)) {
            foreach ($widtharray as $column => $width) {
                $sheet->getColumnDimension($column)->setWidth($width);
            }
        }
        if (!empty($settings)) {
            foreach ($settings as $fun => $value) {
                if (is_array($value)) {
                    foreach ($value as $v) {
                        $sheet->$fun($v);
                    }
                } else {
                    $sheet->$fun($value);
                }
            }
        }
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }
}
